import type {
  RouteLocationNormalizedLoadedGeneric,
  RouteRecordName
} from "vue-router"
export const useTagsView = defineStore("tag", () => {
  const visitedViews = ref<RouteLocationNormalizedLoadedGeneric[]>([])

  const addView = (view: RouteLocationNormalizedLoadedGeneric) => {
    // 根据path去重
    const exists = visitedViews.value.some((v) => v.path === view.path)
    addCacheView(view) // 是否需要添加到缓存中
    if (exists) return

    // 添加视图时设置默认title
    const newView = {
      ...view,
      title: view.meta?.title || "tag-name"
    }
    visitedViews.value.push(newView)
  }
  const delView = (view: RouteLocationNormalizedLoadedGeneric) => {
    const index = visitedViews.value.findIndex((v) => v.path === view.path)
    if (index > -1) {
      visitedViews.value.splice(index, 1)
    }
    delCachedView(view)
  }

  const cachedViews = ref<RouteRecordName[]>([])
  const addCacheView = (view: RouteLocationNormalizedLoadedGeneric) => {
    if (cachedViews.value.includes(view.name!)) return
    if (!view.meta.noCache) {
      // 需要缓存
      cachedViews.value.push(view.name!)
    }
  }
  const delCachedView = (view: RouteLocationNormalizedLoadedGeneric) => {
    const index = cachedViews.value.findIndex((v) => v === view.name)
    if (index > -1) {
      cachedViews.value.splice(index, 1)
    }
  }

  const delAllView = () => {
    visitedViews.value = visitedViews.value.filter((tag) => tag.meta.affix)
    cachedViews.value = []
  }

  const delOthersViews = (view: RouteLocationNormalizedLoadedGeneric) => {
    visitedViews.value = visitedViews.value.filter(
      (tag) => tag.meta.affix || tag.path === view.path
    )
    // 留下当前缓存
    cachedViews.value = cachedViews.value.filter((name) => name === view.name)
  }

  return {
    visitedViews,
    addView,
    delView,
    cachedViews,
    addCacheView,
    delCachedView,
    delAllView,
    delOthersViews
  }
})
